package com.spdd.mt.app.api;

import com.spdd.mt.biz.manager.channel.SpddService;
import com.spdd.mt.biz.manager.model.request.SpddReq;
import com.spdd.mt.biz.manager.model.request.SpddReqNotifyContent;
import com.spdd.mt.common.util.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 充值回调接口
 */
@Slf4j
@RestController
@RequestMapping("/notify")
public class NotifyController {

    @Autowired
    private SpddService spddService;

    @RequestMapping(value = "/callback/{name}", method = {RequestMethod.GET, RequestMethod.POST})
    public void callback(@PathVariable("name") String name, @RequestBody SpddReq<SpddReqNotifyContent> spddReq, HttpServletResponse response) {
        log.info("回调接口，收到 {} 的回调通知，回调参数:{}", name, JacksonUtils.toJson(spddReq));

        // 处理美团的回调信息
        boolean result = spddService.dealNotify(spddReq.getReqBody().getContent());

        writeJson(response, result);
    }

    private void writeJson(HttpServletResponse response, boolean success) {
        String data = "{\"respBody\":{\"resp\":{\"code\":\"00\",\"msg\":\"ok\"}}}";
        if (!success) {
            data = "{\"respBody\":{\"resp\":{\"code\":\"01\",\"msg\":\"fail\"}}}";
        }
        try (PrintWriter out = response.getWriter()) {
            out.write(data);
            out.flush();
        } catch (IOException e) {
            log.error("SPDD回调，回调报文处理后写入响应失败", e);
        }
    }
}
